package com.boss.salary.controller;


import com.boss.api.dto.ApiResultDTO;
import com.boss.common.base.BasicinfoBaseController;
import com.boss.common.entity.PageDTO;
import com.boss.common.service.ICommonService;
import com.boss.common.util.PageUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.salary.dao.IAgencyVerifyDao;
import com.boss.salary.entity.AgencyVerify;
import com.boss.salary.entity.OperrateLogs;
import com.boss.salary.entity.SalaryMonthEnd;
import com.boss.salary.entity.SalaryRental;
import com.boss.salary.service.IAgencyVerifyService;
import com.boss.salary.service.IOperrateLogsService;
import com.boss.salary.service.IRedisService;
import com.boss.salary.service.ISalaryHistoryService;
import com.boss.sys.ca.user.dto.UserDTO;
import com.boss.sys.utils.SysUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/salaryHistoryController", produces = MediaType.APPLICATION_JSON)
public class SalaryHistoryController extends BasicinfoBaseController {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(SalaryHistoryController.class);
    public final static String Executing = "Executing";
    @Autowired
    private ISalaryHistoryService iSalaryHistoryService;

    @Autowired
    private ICommonService iCommonService;

    @Autowired
    private IOperrateLogsService iOperrateLogsService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IAgencyVerifyService agencyVerifyService;
    @Autowired
    private IAgencyVerifyDao iAgencyVerifyDao;

    /**
     * 月结
     * @return
     */
    @PostMapping("/saveMonthEnd")
    public ApiResultDTO saveMonthEnd(@RequestHeader("X-Token") String tokenid,@RequestBody List<AgencyVerify> agencyVerifies) throws Exception {
//@RequestBody List<String> monthEndAgencyIds，
            UserDTO userDTO = getUser(tokenid);
        try {
            Map<String,String> requestMap=new HashMap<>();
            Object re=redisService.get(userDTO.getProvince()+"lunarKnot");
            List<AgencyVerify> agencyVerifyList=agencyVerifyService.queryAgencyVerify(agencyVerifies);

            //查询缓存中该区划是否有在执行的生成操作
            if(!SysUtils.isNullOrEmpty(re)){
                //将月结所有id遍历存入集合中
                List<String> monthEndAgencyIds = new ArrayList<>();
                for(AgencyVerify agencyVerify:agencyVerifies){
                    monthEndAgencyIds.add(agencyVerify.getAgencyId());
                }
                // 查询需要的月份将月份传给agencyVerify1对象
                List<AgencyVerify> agencyVerifyLists = iAgencyVerifyDao.getAgencyVerifyByAgencyIds(monthEndAgencyIds);
                AgencyVerify agencyVerify1=new AgencyVerify();
                //循环如果有月份就直接传给agencyVerify1对象并跳出循环
                for(AgencyVerify agencyVerify:agencyVerifyLists) {
                    if (null != agencyVerify.getSalaryMonth() && !"null".equals(agencyVerify.getSalaryMonth())) {
                        agencyVerify1.setSalaryMonth(agencyVerify.getSalaryMonth());
                        break;
                    }
                }
                //月份和区划和一个lunarKnot变成uuid 并将值存入

                String uuid="2021-"+userDTO.getProvince()+"-lunarKnot";
                //String uuid=agencyVerify1.getSalaryMonth()+"-"+userDTO.getProvince()+"lunarKnot";
                requestMap.put("guid",uuid);
                requestMap.put("已执行月结操作，请稍后刷新查看",Executing);
                return ApiResultDTO.success(requestMap);
            }

            if(!SysUtils.isNullOrEmpty(agencyVerifyList)&&agencyVerifyList.size()>0){
                return ApiResultDTO.error(null, "存在已月结单位，请刷新重试");
            }
            redisService.put(userDTO.getProvince()+"lunarKnot", 1);//添加执行控制，避免重复操作
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setOperateName("财政审核--月结--月结");
            iOperrateLogsService.saveOperrateLogs(operrateLogs);
            String province = userDTO.getProvince();
            Integer year = userDTO.getYear();
            Map<String,String> map =iSalaryHistoryService.saveMonthEnd(year, province, agencyVerifies);
//            redisService.del(userDTO.getProvince()+"lunarKnot");
            return ApiResultDTO.success(map);
//            return ApiResultDTO.success(null, "月结成功");
        } catch (Exception e) {

            redisService.del(userDTO.getProvince()+"lunarKnot");
            logger.error("月结时发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "月结失败");
        }
    }
    /**
     * 查看月结进度
     * @param uuid
     * @return
     */
    @GetMapping("/getPaymentPercent")
    public ApiResultDTO  getPaymentPercent(@RequestParam(value = "uuid") String uuid,@RequestHeader("X-Token") String tokenid){
        try {
            UserDTO userDto = getUser(tokenid);
            Object re = redisService.get(uuid);

            if ("S".equals(re) || (re != null && re.toString().startsWith("F"))) {
                redisService.del(uuid);
                Object generateSalaryState = redisService.get(uuid);
                if(generateSalaryState!=null) {
                    redisService.del(uuid);
                }
            }
            return ApiResultDTO.success(re);
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("月结失败", e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }
    /**
     * 撤销月结前校验
     * @param agencyIds
     * @param salaryMonth
     * @return
     */
    @PostMapping("/checkRevokeMonthEnd")
    public ApiResultDTO checkRevokeMonthEnd(@RequestParam("agencyIds") List<String> agencyIds, @RequestParam("month") String salaryMonth) {
        try {
            Map<String, Object> result = iSalaryHistoryService.checkRevokeMonthEnd(agencyIds, salaryMonth);
            return ApiResultDTO.success(result);
        } catch (Exception e) {
            logger.error("撤销月结时发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销月结失败");
        }
    }

    /**
     * 撤销月结
     * @param salaryMonthEnd
     * @return
     */
    @PostMapping("/revokeMonthEnd")
    public ApiResultDTO revokeMonthEnd(@RequestHeader("X-Token") String tokenid,@RequestBody SalaryMonthEnd salaryMonthEnd) {
        try {
            UserDTO userDTO = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setOperateName("财政审核--月结--撤销月结");
            operrateLogs.setAgencyId(salaryMonthEnd.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            iSalaryHistoryService.revokeMonthEnd(salaryMonthEnd);
            return ApiResultDTO.success(null, "撤销月结成功");
        } catch (Exception e) {
            logger.error("撤销月结时发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "撤销月结失败");
        }
    }


    /**
     * 获取接收单位数据
     * @return
     */
    @GetMapping("/getSalaryList")
    public ApiResultDTO getSalary(@RequestHeader("X-Token")String tokenid,
                                  @RequestParam(value = "page") String page,
                                  @RequestParam(value = "limit") String limit,
                                  @RequestParam(value = "flag") String flag,
                                  @RequestParam(value = "menuid") String menuid,
                                  @RequestParam(value = "agencyId") String agencyId,
                                  @RequestParam(value = "gzlx",required = false) String gzlx,
                                  @RequestParam(value = "rylx",required = false) String rylx,
                                  @RequestParam(value = "bddw",required = false) String bddw,
                                  @RequestParam(value = "dwmc",required = false) String dwmc){

        try {
            UserDTO userDTO = getUser(tokenid);
            Map<String, Object> queryParam =new HashMap<>();
            queryParam.put("flag",flag);
            queryParam.put("agencyId",agencyId);
            queryParam.put("menuid",menuid);
            queryParam.put("gzlx",gzlx);
            queryParam.put("rylx",rylx);
            queryParam.put("bddw",bddw);
            queryParam.put("dwmc",dwmc);
            queryParam.put("mofDivCode", userDTO.getProvince());
            List<String> childrenId = iCommonService.getAgencyChildrenId(userDTO, agencyId);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page,limit);
            PageDTO<SalaryRental> pageDTO = iSalaryHistoryService.getSalary(userDTO, paginationDTO, queryParam,childrenId);
            if(null == pageDTO){
                return ApiResultDTO.error(ERROR_RSCODE,"数据为空");
            }else{
                return ApiResultDTO.success(pageDTO,null);
            }

        } catch (Exception e) {
            logger.error("获取工资数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取工资数据发生异常");
        }
    }

    /**
     * 获取未月结的数据-分页
     * @return
     */
    @GetMapping("/getSalaryMonthEndPage")
    public ApiResultDTO getSalaryMonthEndPage(@RequestHeader("X-Token")String tokenid,
                                              @RequestParam(value = "page") String page,
                                              @RequestParam(value = "limit") String limit,
                                              @RequestParam(value = "agencyId") String agencyId){
        try {
            String province=getUser(tokenid).getProvince();
            UserDTO userDTO = getUser(tokenid);
            List<String> childrenIds = iCommonService.getAgencyChildrenId(userDTO, agencyId);
            Map<String, Object> queryParam =new HashMap<>();
            queryParam.put("province",province);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page,limit);
            PageDTO<SalaryRental> pageDTO = iSalaryHistoryService.getSalaryMonthEndPage(paginationDTO, queryParam, childrenIds);
            return ApiResultDTO.success(pageDTO,null);
        } catch (Exception e) {
            logger.error("获取未月结的数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取未月结的数据发生异常");
        }
    }

    /**
     * 获取月结的数据-分页
     * @return
     */
    @GetMapping("/getSalaryMonthHistoryPage")
    public ApiResultDTO getSalaryMonthHistoryPage(@RequestHeader("X-Token")String tokenid,
                                                  @RequestParam(value = "page") String page,
                                                  @RequestParam(value = "limit") String limit,
                                                  @RequestParam(value = "agencyId") String agencyId,
                                                  @RequestParam(value = "month") String month){
        try {
            UserDTO userDTO = getUser(tokenid);
            List<String> childrenIds = iCommonService.getAgencyChildrenId(userDTO, agencyId);
            Map<String, Object> queryParam =new HashMap<>();
            queryParam.put("month", month);
            queryParam.put("province",userDTO.getProvince());
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page,limit);
            PageDTO<SalaryRental> pageDTO = iSalaryHistoryService.getSalaryMonthHistoryPage(paginationDTO, queryParam, childrenIds);
            return ApiResultDTO.success(pageDTO,null);
        } catch (Exception e) {
            logger.error("获取月结的数据发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取月结的数据发生异常");
        }
    }

    /**
     * 十三月工资：条件查询列表
     * @param agencyId
     * @param salaryMonth
     * @param salaryItem
     * @return
     */
    @GetMapping("/querySalaryHistoryPage")
    public ApiResultDTO querySalaryHistoryPage(@RequestHeader("X-Token") String tokenid,
                                               @RequestParam("agencyId") String agencyId,
                                               @RequestParam("salaryMonth") String salaryMonth,
                                               @RequestParam("salaryItem") List<String> salaryItem){
        try {
//            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page,limit);
            UserDTO userDTO = getUser(tokenid);
            List<Map<String, Object>> page = iSalaryHistoryService.getSalaryHistoryPage(agencyId, salaryMonth, salaryItem,userDTO.getProvince());
            return ApiResultDTO.success(page);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ApiResultDTO.error(ERROR_RSCODE,"查询失败");
        }
    }
}
